package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.*;
import com.qingcheng.entity.PageResult;
import com.qingcheng.entity.SplitOrder;
import com.qingcheng.pojo.order.*;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.OrderItemService;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.util.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 返回全部记录
     *
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 条件查询
     *
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    @Override
    public Orders findOrdersById(String id) {
        Orders orders = new Orders();
        //根据订单id查询订单主表数据
        //将查询结果封装到订单组合对象
        orders.setOrder(orderMapper.selectByPrimaryKey(id));
        //构建example对象用于查询订单明细列表 根据订单id查询
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", id);
        //将查询结果封装到订单组合对象
        orders.setOrderItems(orderItemMapper.selectByExample(example));
        return orders;
    }

    @Autowired
    private CartService cartService;

    @Reference
    private SkuService skuService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 新增
     *
     * @param order
     */
    @Transactional
    public Map<String, Object> add(Order order) {

        //1.获取选中的购物车
        List<Map<String, Object>> cartList = cartService.findNewOrderItemList(order.getUsername());
        List<OrderItem> orderItemList = cartList.stream().filter(cart -> (boolean) cart.get("checked"))
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());

        //2.扣减库存
        if (!skuService.deductionStock(orderItemList)) {
            throw new RuntimeException("库存不足！");
        }
        try {
            //3.保存订单主表
            order.setId(idWorker.nextId() + "");

            IntStream numStream = orderItemList.stream().mapToInt(OrderItem::getNum);
            IntStream moneytStream = orderItemList.stream().mapToInt(OrderItem::getMoney);
            int totalNum = numStream.sum();
            int totalMoney = moneytStream.sum();
            int preMoney = cartService.preferential(order.getUsername());  //满减优惠金额

            order.setTotalNum(totalNum);//总数量
            order.setTotalMoney(totalMoney); //总金额
            order.setPreMoney(preMoney);//优惠金额
            order.setPayMoney(totalMoney - preMoney);//支付金额
            order.setCreateTime(new Date());//订单创建时间
            order.setOrderStatus("0");//订单状态
            order.setPayStatus("0");//支付状态
            order.setConsignStatus("0");//发货状态

            orderMapper.insert(order);


            //4.保存订单明细表
            //打折比例
            double proportion = (double) order.getPayMoney() / totalMoney;

            for (OrderItem orderItem : orderItemList) {
                orderItem.setId(idWorker.nextId() + "");
                orderItem.setOrderId(order.getId());
                orderItem.setPayMoney((int) (orderItem.getMoney() * proportion));

                orderItemMapper.insert(orderItem);
            }

            //int x=1/0;
        } catch (Exception e) {
            e.printStackTrace();
            //发送回滚消息
            rabbitTemplate.convertAndSend("", "queue.skuback", JSON.toJSONString(orderItemList));
            throw new RuntimeException("创建订单失败");
        }

        //5.清除购物车
        cartService.deleteCheckedCart(order.getUsername());

        Map map = new HashMap();
        map.put("ordersn", order.getId());
        map.put("money", order.getPayMoney());
        return map;

    }

    /**
     * 修改
     *
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }


    @Autowired
    private OrderLogMapper orderLogMapper;


    @Autowired
    private OrderConfigMapper orderConfigMapper;


    @Override
    @Transactional
    public void updatePayStatus(String orderId, String transactionId) {
        System.out.println("调用修改订单状态");
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order != null && "0".equals(order.getPayStatus())) {
            //修改订单状态等信息
            order.setPayStatus("1");//支付状态
            order.setOrderStatus("1");//订单状态
            order.setUpdateTime(new Date());//修改日期
            order.setPayTime(new Date());//支付日期
            order.setTransactionId(transactionId);//交易流水号
            orderMapper.updateByPrimaryKeySelective(order);//修改

            //记录订单日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId() + "");
            orderLog.setOperater("system");//系统
            orderLog.setOperateTime(new Date());//操作时间
            orderLog.setOrderStatus("1");//订单状态
            orderLog.setPayStatus("1");//支付状态
            orderLog.setRemarks("支付流水号：" + transactionId);//备注
            orderLog.setOrderId(orderId);
            orderLogMapper.insert(orderLog);
        }
    }

    @Override
    @Transactional //多表操作，添加事务控制
    public void batchSend(String[] ids) {
        for (String id : ids) {
            //遍历 订单id列表， 将每一个订单的状态修改为已发货
            Order order = orderMapper.selectByPrimaryKey(id);
            //订单状态为未发货 发货状态为未发货的订单才修改状态
            if (order.getOrderStatus() == "1" && order.getConsignStatus() == "0") {
                order.setOrderStatus("2");//订单状态 已发货
                order.setConsignStatus("2"); //发货状态 已发货
                order.setConsignTime(new Date());//发货时间
                orderMapper.updateByPrimaryKeySelective(order);

                //记录订单日志
                OrderLog orderLog = new OrderLog();
                orderLog.setId(idWorker.nextId() + "");
                orderLog.setRemarks("订单发货");
                orderLog.setConsignStatus("2"); //已发货
                orderLog.setOrderId(order.getId()); //订单id
                orderLog.setOperateTime(new Date()); //操作时间
                orderLog.setOperater("订单发货");
                orderLog.setOrderStatus("2"); //订单状态
                orderLogMapper.insert(orderLog);
            }
        }
    }

    @Override
    public void orderTimeOutLogic() {
        //订单超时未付款 自动关闭
        //查询超时时间
        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);
        Integer orderTimeout = orderConfig.getOrderTimeout(); //超时时间（分） 60
        LocalDateTime localDateTime =
                LocalDateTime.now().minusMinutes(orderTimeout); //得到超时的时间点
        //设置查询条件
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThan("createTime", localDateTime);//创建时间小于超时时间
        criteria.andEqualTo("orderStatus", "0");//未付款的
        criteria.andEqualTo("isDelete", "0");//未删除的
        //查询超时订单
        List<Order> orders = orderMapper.selectByExample(example);
        for (Order order : orders) {
            //记录订单变动日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOperater("system");// 系统
            orderLog.setOperateTime(new Date());//当前日期
            orderLog.setOrderStatus("4");
            orderLog.setPayStatus(order.getPayStatus());
            orderLog.setConsignStatus(order.getConsignStatus());
            orderLog.setRemarks("超时订单，系统自动关闭");
            orderLog.setOrderId(order.getId());
            orderLogMapper.insert(orderLog);
            //更改订单状态
            order.setOrderStatus("4");
            order.setCloseTime(new Date());//关闭日期
            orderMapper.updateByPrimaryKeySelective(order);
        }
    }

    /**
     * 合单
     *
     * @param orderId1 主订单号
     * @param orderId2 从订单号
     */
    @Override
    public void merge(String orderId1, String orderId2) {
        //实现思路
        // 1. 根据orderId1查询出Order和List<OrderItem>
        List<OrderItem> orderItemList1 = getOrderItemListByOrderId(orderId1);
        Order order1 = orderMapper.selectByPrimaryKey(orderId1);
        // 2. 根据orderId2查询出Order和List<OrderItem>
        List<OrderItem> orderItemList2 = getOrderItemListByOrderId(orderId2);
        Order order2 = orderMapper.selectByPrimaryKey(orderId2);
        // 3. 新创建一个Order对象名为newOrder，
        Order newOrder = createNewOrder(order1);
        // 4. 遍历orderId1的List<OrderItem>和orderId2的List<OrderItem>，找到相同的数据合并
        List<OrderItem> newOrderItem = mergeOrderItem(orderItemList1, orderItemList2);
        // 5. 把处理好之后的List<OrderItem>每一个元素的orderId设置成newOrder的id
        Integer totalMoney = 0;
        Integer totalNum = 0;
        for (OrderItem orderItem : newOrderItem) {
            orderItem.setOrderId(newOrder.getId());
            orderItem.setId(idWorker.nextId() + "");
            // 6. 统计newOrder的金额合计，数量合计，更新到newOrder中
            totalNum += orderItem.getNum();
            totalMoney += orderItem.getMoney();
            //TODO 把其他的需要累加的字段在检查下
            orderItemMapper.insert(orderItem);
        }
        // 7. 修改orderId1的Order和orderId2的Order状态为已关闭
        order1.setOrderStatus("4");  //TODO 关闭应该是几 要确定下，这只是随便写的
        order2.setOrderStatus("4");  //TODO 关闭应该是几 要确定下，这只是随便写的
        newOrder.setTotalNum(totalNum);
        newOrder.setTotalMoney(totalMoney);
        // 8. 记录订单日志
        //TODO 按照要求记录
        // 9. 保存所有改动
        orderMapper.updateByPrimaryKey(order1);
        orderMapper.updateByPrimaryKey(order2);
        orderMapper.updateByPrimaryKey(newOrder);
    }

    /**
     * 拆单
     *
     * @param splitOrders [{orderItemId:1,num:2}]
     */
    @Override
    public void split(List<SplitOrder> splitOrders) {
        Order newOrder = new Order();
        Order order = null;
        List<OrderItem> newOrderItems = new ArrayList<>();
        //实现思路
        for (SplitOrder splitOrder : splitOrders) {
            //1. 根据orderItemId找到OrderItem对象
            OrderItem orderItem = orderItemMapper.selectByPrimaryKey(splitOrder.getOrderItemId());
            //2. 根据orderItemId对象的OrderId找到Order对象
            orderMapper.selectByPrimaryKey(orderItem.getOrderId());
            //3. 新创建一个Order对象，数据来源刚才查询到的Order对象
            BeanUtils.copyProperties(order, newOrder);
            newOrder.setId(idWorker.nextId() + "");
            if (orderItem.getNum().equals(splitOrder.getNum())) {
                //4. 判断拆分数量是否等于OrderItem对象的数量，是则直接设置OrderItem的OrderId为新创建Order对象id即可，修改老的Order对象的金额数量， 新的Order对象金额数量计算。
                orderItem.setOrderId(newOrder.getId());
            } else {
                //5. 如果判断为否且数量合法，则新创建一个OrderItem对象,除了数量金额信息，其他全部来自老的OrderItem，数量和金额用拆分出的金额计算， 设置老订单的OrderItem数量金额为减去拆分出去的数量和金额，设置老订单的金额数量，设置新的订单的金额数量。
                OrderItem newOrderItem = new OrderItem();
                BeanUtils.copyProperties(orderItem, newOrderItem);
                newOrderItem.setId(idWorker.nextId() + "");
                newOrderItem.setOrderId(newOrder.getId());
                newOrderItem.setNum(splitOrder.getNum());
                // TODO 根据数量计算金额 补全其他字段

                orderItem.setNum(orderItem.getNum() - splitOrder.getNum());
                // TODO 根据数量计算金额 补全其他字段

                newOrderItems.add(newOrderItem);
            }
            //6. 记录订单日志
            //TODO 按照要求记录
        }
        //7. 保存所有改动
        //TODO 老的Order对象处理 要把值进行重新计算
        //TODO 新的Order对象处理 要把值进行重新计算后在保存
    }

    @Autowired
    private OrderAnalyzeMapper orderAnalyzeMapper;

    /**
     * 按照要求 每天 构建 昨天的交易数据
     */
    @Override
    public void createData() {
        OrderAnalyze orderAnalyze = new OrderAnalyze();
        //查询昨天的统计数据
        LocalDate localDate = LocalDate.now().minusDays(1);

        List<Map> order1 = orderMapper.getOrderNumber(localDate.toString());
        List<Map> order2 = orderMapper.getOrderCount(localDate.toString());
        List<Map> order3 = orderMapper.getValidOrderCount(localDate.toString());
        List<Map> order4 = orderMapper.getReturnMoney(localDate.toString());
        List<Map> order5 = orderMapper.getPayCount(localDate.toString());
        List<Map> order6 = orderMapper.getPayOrderCount(localDate.toString());

        orderAnalyze.setOrderNumber(Integer.parseInt(order1.get(0).toString())); //下单人数
        orderAnalyze.setOrderCount(Integer.parseInt(order2.get(0).toString())); //订单数，
        orderAnalyze.setOrderUnitNumber(Integer.parseInt(order2.get(1).toString())); //下单件数，
        orderAnalyze.setOrderTotalMoney(Integer.parseInt(order2.get(2).toString())); //下单金额
        orderAnalyze.setValidOrderCount(Integer.parseInt(order3.get(0).toString())); //有效订单数
        orderAnalyze.setReturnMoney(Integer.parseInt(order4.get(0).toString())); //退款金额
        orderAnalyze.setPayCount(Integer.parseInt(order5.get(0).toString())); //付款人数
        orderAnalyze.setPayOrderCount(Integer.parseInt(order6.get(0).toString())); //付款订单数
        orderAnalyze.setPayOrderUnitNumber(Integer.parseInt(order6.get(1).toString())); //付款件数
        orderAnalyze.setPayTotalMoney(Integer.parseInt(order6.get(2).toString())); //付款金额
        orderAnalyze.setPerCustomerTransaction(orderAnalyze.getOrderTotalMoney() / orderAnalyze.getOrderNumber()); //客单价
        orderAnalyze.setViewCount(Integer.parseInt(order1.get(0).toString())); //浏览人数
        orderAnalyze.setOrderDate(order1.get(0).toString()); //交易日

        orderAnalyzeMapper.insert(orderAnalyze);
    }

    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 订单id
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andLike("id", "%" + searchMap.get("id") + "%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if (searchMap.get("payType") != null && !"".equals(searchMap.get("payType"))) {
                criteria.andLike("payType", "%" + searchMap.get("payType") + "%");
            }
            // 物流名称
            if (searchMap.get("shippingName") != null && !"".equals(searchMap.get("shippingName"))) {
                criteria.andLike("shippingName", "%" + searchMap.get("shippingName") + "%");
            }
            // 物流单号
            if (searchMap.get("shippingCode") != null && !"".equals(searchMap.get("shippingCode"))) {
                criteria.andLike("shippingCode", "%" + searchMap.get("shippingCode") + "%");
            }
            // 用户名称
            if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                criteria.andLike("username", "%" + searchMap.get("username") + "%");
            }
            // 买家留言
            if (searchMap.get("buyerMessage") != null && !"".equals(searchMap.get("buyerMessage"))) {
                criteria.andLike("buyerMessage", "%" + searchMap.get("buyerMessage") + "%");
            }
            // 是否评价
            if (searchMap.get("buyerRate") != null && !"".equals(searchMap.get("buyerRate"))) {
                criteria.andLike("buyerRate", "%" + searchMap.get("buyerRate") + "%");
            }
            // 收货人
            if (searchMap.get("receiverContact") != null && !"".equals(searchMap.get("receiverContact"))) {
                criteria.andLike("receiverContact", "%" + searchMap.get("receiverContact") + "%");
            }
            // 收货人手机
            if (searchMap.get("receiverMobile") != null && !"".equals(searchMap.get("receiverMobile"))) {
                criteria.andLike("receiverMobile", "%" + searchMap.get("receiverMobile") + "%");
            }
            // 收货人地址
            if (searchMap.get("receiverAddress") != null && !"".equals(searchMap.get("receiverAddress"))) {
                criteria.andLike("receiverAddress", "%" + searchMap.get("receiverAddress") + "%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if (searchMap.get("sourceType") != null && !"".equals(searchMap.get("sourceType"))) {
                criteria.andLike("sourceType", "%" + searchMap.get("sourceType") + "%");
            }
            // 交易流水号
            if (searchMap.get("transactionId") != null && !"".equals(searchMap.get("transactionId"))) {
                criteria.andLike("transactionId", "%" + searchMap.get("transactionId") + "%");
            }
            // 订单状态
            if (searchMap.get("orderStatus") != null && !"".equals(searchMap.get("orderStatus"))) {
                criteria.andLike("orderStatus", "%" + searchMap.get("orderStatus") + "%");
            }
            // 支付状态
            if (searchMap.get("payStatus") != null && !"".equals(searchMap.get("payStatus"))) {
                criteria.andLike("payStatus", "%" + searchMap.get("payStatus") + "%");
            }
            // 发货状态
            if (searchMap.get("consignStatus") != null && !"".equals(searchMap.get("consignStatus"))) {
                criteria.andLike("consignStatus", "%" + searchMap.get("consignStatus") + "%");
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andLike("isDelete", "%" + searchMap.get("isDelete") + "%");
            }

            // 数量合计
            if (searchMap.get("totalNum") != null) {
                criteria.andEqualTo("totalNum", searchMap.get("totalNum"));
            }
            // 金额合计
            if (searchMap.get("totalMoney") != null) {
                criteria.andEqualTo("totalMoney", searchMap.get("totalMoney"));
            }
            // 优惠金额
            if (searchMap.get("preMoney") != null) {
                criteria.andEqualTo("preMoney", searchMap.get("preMoney"));
            }
            // 邮费
            if (searchMap.get("postFee") != null) {
                criteria.andEqualTo("postFee", searchMap.get("postFee"));
            }
            // 实付金额
            if (searchMap.get("payMoney") != null) {
                criteria.andEqualTo("payMoney", searchMap.get("payMoney"));
            }

        }
        return example;
    }


    private List<OrderItem> getOrderItemListByOrderId(String orderId) {
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", orderId);
        return orderItemMapper.selectByExample(example);
    }


    private Order createNewOrder(Order sourceOrder) {
        Order order = new Order();
        //从orderId1对应的Order对象中取出数据赋值到newOrder
        BeanUtils.copyProperties(sourceOrder, order);
        //设置新的订单id
        order.setId(idWorker.nextId() + "");
        return order;
    }


    private List<OrderItem> mergeOrderItem(List<OrderItem> orderItems1, List<OrderItem> orderItems2) {
        List<OrderItem> newOrderItemList = new ArrayList<>();
        newOrderItemList.addAll(orderItems1);
        newOrderItemList.addAll(orderItems2);
        // TODO 查询出重复的orderItem并处理,最少需要根据SkuId和价格
        return newOrderItemList;
    }

}
